requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        filer: '../plugins/fileinput/js/new/jquery.filer'
    },
    shim: {
        'filter':['jquery']
    }
});
define([ 'jquery', 'jquery_route', 'arttemplateUtil' ,'common','config','pageJs','filer','validform','wdatePicker' ], function($,
		jquery_route, arttemplateUtil,common,config,pageJs,filer) {
	
	$.controller("controller.market.coupon", function($model, $tplHtml, $defobj,
			$modelobj, $paramobj, $this) {
		//渲染到页面方法
		$model($defobj);	
		var param={};
		var initMarkData = function(){
			
			param.coupon_name=$('#serchForm #coupon_name').val();
			param.goods_name=$('#serchForm #goods_name').val();
			param.delivery_times=$('#serchForm #delivery_times').val();
			param.first_valid_date=$('#serchForm #first_valid_date').val();
			param.last_valid_date=$('#serchForm #last_valid_date').val();
			param.goods_price=$('#serchForm #goods_price').val();
			param.coupon_status=$('#serchForm #coupon_status').val();
			common.ajax_request2('post','/api/seller/v1/queryCouponList',param,function($data,$code){
				$defobj.data = $data;
				if(typeof $defobj.data != 'undefined'){
					pageJs.setPage($defobj.data.pageNo,$defobj.data.totalPage,$defobj.data.totalCount,callback);
				}
				$('#coupon_list').html(arttemplateUtil.template.compile($.setHTML('market/templates/coupon_tpl.html'))($defobj));
				initClick();
				layer.closeAll('loading'); //关闭加载层
			});
		}
		
		var _logsFrm=$('#couponBody #serchForm');
		
		//查询验证
		var validserchform = $("#serchForm").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false
		});
		// 搜索
		$('#couponBody #serchForm .serchBtn').off('click').on('click',function(){
			if(validserchform.check()){
				param.pageNo=1;
				initMarkData();
			}
		});
		// 重置
		$('#couponBody #serchForm .resetBtn').off('click').on('click',function(){
			if(_logsFrm.length>0){
				_logsFrm[0].reset();
			}
			$("#serchForm input").removeClass("Validform_error");
			$("#serchForm .Validform_checktip").removeClass("Validform_wrong").html("");
			param.pageNo=1;
			initMarkData();
		});
		
		
		
		//分页回调
		var callback = function(page){
			param.pageNo=page
			initMarkData();
		}
		
		var initClick = function(){
			
			//新增
			var editButtonfun = function(obj){
				common.loading();
				$('#coupon_modal').modal('show');
				var $goods_id="";
				var $skuid = "";
				var $label_type = "";
				$defobj.imgRoot=config.imgRoot();
				if($(obj).attr("data-id") != undefined){//编辑状态
					//获取具体优惠券
					common.ajax_request2('post','/api/seller/v1/queryCouponById',{id:$(obj).attr("data-id")},function($data,$code){
						if($code==200){
							$defobj.data = $data;
							if(Number($data.valid_begintime)>new Date().getTime()){
								$defobj.data.curDate = new Date().getTime();
							}else{
								$defobj.data.curDate = $data.valid_begintime;
							}
							$goods_id = $data.goods_id;
							$skuid = $data.skuid;
							$label_type = $data.label_type;
							$('#coupon_content').html(arttemplateUtil.template.compile($.setHTML('market/templates/coupon_edit_tpl.html'))($defobj));
						}
					},false);
				}else{
					$defobj.data = {};
					$defobj.data.curDate = new Date().getTime();
					$('#coupon_content').html(arttemplateUtil.template.compile($.setHTML('market/templates/coupon_edit_tpl.html'))($defobj));
				}
				// 初始化上传功能
				app_couponDetail.uploadInit('#fileinput1');
				$("#goods_label_type").val($label_type);
				//设置商品信息
				common.ajax_request2('post','/api/seller/v1/queryCouponGoodsList',{},function($data,$code){
					if($code==200){
						var goodsbox=$("#editForm select[name=goods_id]");
						goodsbox.empty();
						goodsbox.append('<option value>请选择</option>');
						$.each($data.records,function(index,data){
							if($goods_id !=""){
								if($goods_id==data.id){
									goodsbox.append('<option value="'+data.id+'" data-type="'+data.label_type+'" data-price="'+data.goods_current_price+'" selected=true >'+data.goods_name+'</option>');
								}else{
									goodsbox.append('<option value="'+data.id+'" data-type="'+data.label_type+'" data-price="'+data.goods_current_price+'" >'+data.goods_name+'</option>');
								}
							}else{
								goodsbox.append('<option value="'+data.id+'" data-type="'+data.label_type+'" data-price="'+data.goods_current_price+'" >'+data.goods_name+'</option>');
							}
						});
					}

				},false);
				//取默认商品的SKU
				if($goods_id !="" && $label_type==2){
					var _skuid=$("#editForm select[name=skuid]");
					_skuid.empty();
					_skuid.append('<option value>请选择</option>');
					common.ajax_request2('get','/api/seller/v1/queryGoodsSKU',{goodsid:$goods_id},function($data,$code){
						if($code==200){
							$.each($data,function(index,data){
								if($skuid !=""){
									if($skuid==data.id){
										_skuid.append('<option value="'+data.id+'" data-price="'+data.goods_price_old+'" selected=true >'+data.delivery_name+'</option>');
										$("#editForm #goods_price").html(data.goods_price_old);								
									}else{
										_skuid.append('<option value="'+data.id+'" data-price="'+data.goods_price_old+'" >'+data.delivery_name+'</option>');
									}
								}else{
									_skuid.append('<option value="'+data.id+'" data-price="'+data.goods_price_old+'" >'+data.delivery_name+'</option>');
								}
							});
						}
					},false);
					$("#skuid_div").show();
				}else if($goods_id !="" && $label_type==1){
					$("#skuid_div").hide();
				}
				//商品发生改变取SKU
				$("#editForm select[name=goods_id]").on('change',function(){
					$("#editForm #goods_price").html("0");
					var _skuid=$("#editForm select[name=skuid]");
					_skuid.empty();
					_skuid.append('<option value>请选择</option>');
					if($(this).val()!=''){
						if($(this).find("option:selected").attr("data-type")=="2"){
							$("#skuid_div").show();
							$('#skuid').attr("datatype","*");
							common.ajax_request2('get','/api/seller/v1/queryGoodsSKU',{goodsid:$(this).val()},function($data,$code){
								if($code==200){
									$.each($data,function(index,data){
										_skuid.append('<option value="'+data.id+'" data-price="'+data.goods_price_old+'" >'+data.delivery_name+'</option>');
									});
								}
							});
						}else{
							$("#skuid_div").hide();
							$('#skuid').removeAttr("datatype");
							$("#editForm #goods_price").html($(this).find("option:selected").attr("data-price"));
						}
						$("#editForm #goods_label_type").val($(this).find("option:selected").attr("data-type"));
					}else{
						$("#editForm #goods_label_type").val("");
					}
				});
				//设置价格
				$("#editForm select[name=skuid]").on('change',function(){
					if($(this).val()!=''){
						$("#editForm #goods_price").html($(this).find("option:selected").attr("data-price"));
					}else{
						$("#editForm #goods_price").html("0");
					}
				});
				$('#couponBody .editSubmit').off('click').on('click',function(){
					editSubmit(this);
				});	
				layer.closeAll('loading'); //关闭加载层
			}
			
			var editSubmit = function(obj){
				var validaddrForm = $("#editForm").Validform({
					tiptype:4,
					postonce:true,
					isShowRight:false,
					ignoreHidden:true,
					datatype:{"dateCompare":function(gets,obj,curform,regxp){
						var reg = /(^\\s*$)|(^([0-9]{4})-([0-9]{2})-([0-9]{2})$)/;
						if($("#editForm #valid_begintime").val()=="" || $("#editForm #valid_endtime").val()==""){
							return "使用有效期不能为空";
						}else if($("#editForm #valid_begintime").val()>$("#editForm #valid_endtime").val()){
							return "使用有效期开始时间不能大于结束时间";
						}else{
							$("#editForm #valid_endtime").next().remove();
						}
						return true;
					},"logoValia":function(gets,obj,curform,regxp){
						if($("#editForm #coupon_logo").val()==""){
							return "兑换券LOGO不能为空";
						}
						$(obj).next().next().remove()
						return true;
					}},
				});
				if(!validaddrForm.check()){
					return false;
				}
				common.loading();
				$(obj).attr("disabled","disabled");
				common.common_ajax_request('/api/seller/v1/editCouponList',$('#editForm').serializeArray(),false,function(data,code,msg){
					window.layer.msg(msg.businessNote);
					if(msg.businessCode==0){
						$('#coupon_modal').modal('hide');
						layer.closeAll('loading');
						initMarkData();
					}
				},"","post",function(){
					$(".editSubmit").removeAttr("disabled");
				});
			}
			
			//编辑
			$('#couponBody .editCoupon').off('click').on('click',function(){
				editButtonfun(this);
			});
			//删除
			$('#couponBody .delCoupon').off('click').on('click',function(){
				var obj = this;
				layer.confirm('确定要删除兑换券？', {
					  btn: ['确定','取消'] //按钮
					}, function(){
						common.common_ajax_request('/api/seller/v1/delCouponList',{id:$(obj).attr("data-id")},false,function(data,code,msg){
							window.layer.msg(msg.businessNote);
							if(msg.businessCode==0){
								param.pageNo=1;
								initMarkData();
							}
						},"","get");
					}, function(){
					  
				});
			});
			var coupon_name = "";
			var $coupon_status = "";
			var $detail_param={};
			var app_couponDetail = {
					//兑换券分页
					pagefun:function(page){
						//分页回调
						$detail_param.pageNo=page;
						app_couponDetail.initCouponDetail($("#dsc_id").val());
					},
				name:'兑换券详情列表',
				initCouponDetail : function(id) {

					$detail_param.id = id;
					common.ajax_request2('get','/api/seller/v1/queryCouponDetailById',$detail_param,function($data,$code){
						if($code==200){
							$defobj.data = $data;
							$defobj.coupon_status=$coupon_status;
							$('#exchange_list').html(arttemplateUtil.template.compile($.setHTML('market/templates/coupon_view_list_tpl.html'))($defobj));
							$("#chkall_coupon").prop("checked", false);
							pageJs.setPage_dynamic(
									{pageBox:'#view_pageBox',records:'#view_records',page:'#view_page'},
									$data.pageNo,$data.totalPage,$data.totalCount,app_couponDetail.pagefun);
							
							$("#dsc_id").val(id);
							//全选
							$('#coupon_content').off('click','.chkall_coupon').on('click','.chkall_coupon',function(){
								if($("#chkall_coupon").is(':checked')==true){
									$("input:checkbox[name='chksub_coupon']").prop("checked", true);
								}else{
									$("input:checkbox[name='chksub_coupon']").prop("checked", false);
								}
							});
							//子选
							$("input:checkbox[name='chksub_coupon']").each(function(){
								$(this).click(function(){
									var len1=$("input:checkbox[name='chksub_coupon']").length;
									var len2=$("input:checkbox[name='chksub_coupon']:checked").length;
									if(len1==len2){
										$("#chkall_coupon").prop("checked", true);
									}
									if(len1>len2){
										$("#chkall_coupon").prop("checked", false);
									}
								})
							});

						}
					},true);
					
				},
				
				activationCoupon:function(coupon_chk_value) {
					if(coupon_chk_value.length > 0) {
						var confirmW = layer.confirm('确定激活吗？', {
							  btn: ['确定','取消']
						}, function(){
							var param_tmp = [];
							param_tmp.push({"name":"ids","value":coupon_chk_value});
							param_tmp.push({"name":"dsc_id","value":$("#dsc_id").val()})
							common.common_ajax_request('/api/seller/v1/updateActionById',param_tmp,false,function(data,code,msg){
								if(msg.businessCode==0){
									app_couponDetail.initCouponDetail($("#dsc_id").val());
									window.layer.close(confirmW);
								}else{
									if(coupon_chk_value.length==1){
										layer.msg("激活失败");
									}else{
										layer.msg("批量激活失败");
									}
								}
							},"","post");
						}, function(){});
					} else {
						layer.alert("请至少选择一条未激活数据");
					}
				},
				// 图片上传初始化
				uploadInit:function(uploadId){
					$(uploadId).filer({
			            changeInput: '<div class="jFiler-input-dragDrop mb10"><a class="jFiler-input-choose-btn blue-light btn btn-primary">选择图片</a></div>',
			            limit: 1,
			            maxSize: 2,
			            appendTo:null,
			            extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
			            theme: "dragdropbox",
			            uploadFile: {
			                url: config.apiRoot() + "/api/v1/storeUpload",
			                data: config.setFullParameterArr({}),
			                type: 'POST',
			                enctype: 'multipart/form-data',
			                beforeSend: null,
			                success: function(data, el){
			                	var jsondata = $.parseJSON(data); 
			                	if(jsondata.code == "200") {
			                		var _path=jsondata.data.path+jsondata.data.ext;
			                		$(uploadId).parents('.form-group').find('img').attr('src',config.imgRoot()+_path);
			                		$(uploadId).parents('.form-group').find('input[type=hidden]').val(_path);
			                	}
			                },
			                error: function(el){
			                	Common.alert(el.html());
			                    //上传失败的时候把编辑的图片预览窗显示
			                	//$(uploadId).parent().parent().find(".shanchu").parent().parent().show();
			                },
			                statusCode: null,
			                onProgress: null,
			                onComplete: null
			         },
					captions: {
						button: "Choose Files",
						feedback: "Choose files To Upload",
						feedback2: "files were chosen",
						drop: "Drop file here to Upload",
						removeConfirmation: "Are you sure you want to remove this file?",
						errors: {
							filesLimit: "只能选择 {{fi-limit}} 图片上传.",
							filesType: "只能上传图片.",
							filesSize: "{{fi-name}} 太大! 上传文件不超过{{fi-maxSize}} MB.",
							filesSizeAll: "选择的文件太大! 上传文件不超过 {{fi-maxSize}} MB."
						}
					}
			      });
			   }
			}
		
			$('#couponBody .viewCoupon').off('click').on('click',function(){
				$('#coupon_modal').modal('show');
				coupon_name = $(this).attr("data-name");
				$coupon_status = $(this).attr("data-status");
				$detail_param.pageNo=1;
				$defobj.coupon_status=$coupon_status;
				$('#coupon_content').html(arttemplateUtil.template.compile($.setHTML('market/templates/coupon_view_tpl.html'))($defobj));
				app_couponDetail.initCouponDetail($(this).attr("data-id"));
				$detail_param.coupon_no="";
				
				$('#coupon_content .serchBtn').off('click').on('click',function(){
					var validaddr1Form = $("#couponBody #viewForm").Validform({
						tiptype:4,
						postonce:true,
						isShowRight:false
					});
					if(!validaddr1Form.check()){
						return false;
					}
					$detail_param.coupon_no= $("#coupon_content #coupon_no").val();
					app_couponDetail.initCouponDetail($("#dsc_id").val());
				});
				//批量激活
				$('#coupon_content').off('click','.bath_action').on('click','.bath_action',function(){
					var chk_value =[];
					$('input[name="chksub_coupon"]:checked').each(function(index,data){ 
						if($(data).attr("data-status")=="1"){
							chk_value.push($(data).val());
						}
					});
					app_couponDetail.activationCoupon(chk_value);
				});
				
				//激活
				$('#coupon_content').off('click','.actionBtn').on('click','.actionBtn',function(){
					var id = $(this).attr("data-id");
					var chk_value =[]
					chk_value.push(id);
					app_couponDetail.activationCoupon(chk_value);
				});
				
				//导出
				$('#coupon_content').off('click','.exportBtn').on('click','.exportBtn',function(){
					
					$("#excel").attr("action",config.apiRoot()+"/api/seller/v1/exportDetailById");
					
					var html = [];
					html.push("<input name=\"id\" type='hidden' id=\"id\" value=\""+$("#dsc_id").val()+"\" />");
					html.push("<input name=\"coupon_name\" type='hidden' id=\"coupon_name\" value=\""+coupon_name+"\" />");
					$.each(config.setFullParameterArr({}), function(i, item) {
						html.push("<input name=\""+i+"\" type='hidden' id="+i+" value=\""+item+"\" />");
					});
					$("#excel").html(html.join(""));
					$("#excel").submit();
					
				});
				
			});
		}
		
		initMarkData();
		
	});

	var App={
			name:'营销工具'
	};
});